package com.csi.controller.back;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.jwt.JWTUtil;
import com.csi.domain.Employee;
import com.csi.domain.PasswordUpdateRequest;
import com.csi.domain.Result;
import com.csi.domain.vo.EmployeeDetail;
import com.csi.service.EmployeeService;
import com.csi.service.TokenService;
import com.csi.utils.ReturnResults;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@RequestMapping("/employee")
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TokenService tokenService;

    /**
     * produces 属性用于指定该方法响应的数据类型，告诉 Spring 这个方法的响应内容是 application/json 类型，且字符编码为 UTF-8。
     * Employee employee 员工对象
     * @return 请求结果
     */
    @PostMapping(value = "/login", produces = "application/json;charset=utf-8")
    public Object login(@RequestBody Employee employee) {
        Employee employees = employeeService.login(employee.getUsername(), employee.getPassword(),employee.getHotelId());
        if (employees != null) {
            String token = tokenService.generateHotelToken(employees.getId(),employees.getUsername(),employees.getRoleId(),employees.getHotelId());
            return new Result("登录成功！", ReturnResults.ACCESS_SUCCESS, token);
        }
        return new Result("登录失败！用户名或密码错误", ReturnResults.ACCESS_FAILED);

    }

    /**
     * 新增员工
     *
     * @param employee 员工对象
     * @return 请求结果
     */
    @PostMapping(value = "/save", produces = "application/json;charset=utf-8")
    public Object save(@RequestBody Employee employee,HttpServletRequest request) {
        //密码默认身份证号后六位
        String idCard = employee.getIdCard();
        employee.setPassword(idCard.substring(idCard.length() - 6));
        //设置入职时间
        employee.setEntryTime(new Timestamp(System.currentTimeMillis()));
        String token = request.getHeader("token");
        long hotelId = Long.parseLong(JWTUtil.parseToken(token).getPayload("hotelId").toString());
        long createId = Long.parseLong(JWTUtil.parseToken(token).getPayload("employeeId").toString());
        employee.setHotelId(hotelId);
        employee.setCreateId(createId);
        employee.setUsername(PinyinUtil.getPinyin(employee.getName()).replace(" ","")); //设置姓名拼音为用户名


        int saved = employeeService.save(employee);
        if (saved > 0) {
            return new Result("新增员工成功！", ReturnResults.ACCESS_SUCCESS);
        }
        return new Result("新增员工失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 更新员工
     *
     * @param employee 员工对象
     * @return 请求结果
     */
    @PostMapping(value = "/update", produces = "application/json;charset=utf-8")
    public Object update(@RequestBody Employee employee,HttpServletRequest request) {
        String token = request.getHeader("token");
        long handleId = Long.parseLong(JWTUtil.parseToken(token).getPayload("employeeId").toString());
        employee.setHandleId(handleId);
        int updated = employeeService.update(employee);
        if (updated > 0) {
            return new Result("更新员工成功！", ReturnResults.ACCESS_SUCCESS);
        }
        return new Result("更新员工失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 删除员工
     *
     * @param employee 员工对象
     * @return 请求结果
     */
    @GetMapping(value = "/delete", produces = "application/json;charset=utf-8")
    public Object delete( Employee employee,HttpServletRequest request) {
        employee.setLeaveTime(new Timestamp(System.currentTimeMillis()));
        long employeeId = Long.parseLong(JWTUtil.parseToken(request.getHeader("token")).getPayload("employeeId").toString());
        if (employeeId == employee.getId()){
            return new Result("删除员工失败！", ReturnResults.ACCESS_FAILED_NO_POWER);
        }
        int deleted = employeeService.delete(employee);
        if (deleted > 0) {
            return new Result("删除员工成功！", ReturnResults.ACCESS_SUCCESS);
        }
        return new Result("删除员工失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 修改权限
     * @param employee 员工对象
     * @return
     */
    @PostMapping(value = "/modifyRole", produces = "application/json;charset=utf-8")
    public Object modifyRole(@RequestBody Employee employee,HttpServletRequest request) {
        long employeeId = Long.parseLong(JWTUtil.parseToken(request.getHeader("token")).getPayload("employeeId").toString());
        if (employeeId == employee.getId()){
            return new Result("删除员工失败！", ReturnResults.ACCESS_FAILED_NO_POWER);
        }
        employee.setLeaveTime(new Timestamp(System.currentTimeMillis()));
        employee.setHandleId(employeeId);
        int updated = employeeService.modifyRole(employee);
        if (updated > 0) {
            return new Result("修改权限成功！", ReturnResults.ACCESS_SUCCESS);
        }
        return new Result("修改权限失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 根据员工id查找员工
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/findById", produces = "application/json;charset=utf-8")
    public Object find(@RequestParam("id") long id) {
        EmployeeDetail find = employeeService.findById(id);
        if (find != null) {
            return new Result("查找员工成功！", ReturnResults.ACCESS_SUCCESS, find);
        }
        return new Result("查找员工失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 根据员工名字和酒店id查找员工
     * @param username
     * @param hotelId
     * @return
     */
    @GetMapping(value = "/findByName", produces = "application/json;charset=utf-8")
    public Object findByName(@RequestParam("username") String username,@RequestParam("hotelId") long hotelId){
        EmployeeDetail employee =  employeeService.findByName(username,hotelId);
        if (employee != null) {
            return new Result("查找员工成功！", ReturnResults.ACCESS_SUCCESS,employee);
        }
        return new Result("查找员工失败！", ReturnResults.ACCESS_FAILED);
    }

    /**
     * 查询离职员工
     * @param request
     * @return
     */
    @GetMapping("showLeaveByHotelId")
    public Object findLeaveEmployee(HttpServletRequest request){
        long hotelId = Long.parseLong(JWTUtil.parseToken(request.getHeader("token")).getPayload("hotelId").toString());
        List<EmployeeDetail> employees = employeeService.findLeaveEmployee(hotelId);
        if (employees != null && !employees.isEmpty()) {
            return new Result("查找酒店员工成功！", ReturnResults.ACCESS_SUCCESS, employees);
        }
        return new Result("查找酒店员工失败", ReturnResults.ACCESS_FAILED);

    }




    /**
     * 模糊查询
     *
     * @param name
     * @param roleId
     * @param sex
     * @return
     */
    @GetMapping(value = "/showByHotelId", produces = "application/json;charset=utf-8")
    public Object like(@RequestParam(value = "name",defaultValue = "null") String name, @RequestParam(name = "roleId",defaultValue = "-1") long roleId, @RequestParam(name = "sex",defaultValue = "-1") int sex,@RequestParam(name = "pageIndex",defaultValue = "1") int pageIndex,@RequestParam(name = "pageSize",defaultValue = "10") int pageSize, HttpServletRequest request) {
        long hotelId = Long.parseLong(JWTUtil.parseToken(request.getHeader("token")).getPayload("hotelId").toString());
        PageInfo<EmployeeDetail> employeeList = employeeService.findLike(name, roleId, sex,hotelId,pageIndex,pageSize);
        long count =employeeList.getTotal();
        Map<String, Object> response = new HashMap<>();
        response.put("data", employeeList.getList());
        response.put("count", count);
        if (employeeList.getList() != null ) {
            return new Result("查找成功！", ReturnResults.ACCESS_SUCCESS, response);
        }
        return new Result("查找失败！", ReturnResults.ACCESS_FAILED);
    }


    /**
     * 根据角色id查找员工
     * @param roleId
     * @return
     */
    @GetMapping(value = "/findByRole")
    public Object findByRole(@RequestParam("id") long roleId){
        List<Employee> employeeList = employeeService.findByRole(roleId);
        if (employeeList != null && !employeeList.isEmpty()) {
            return new Result("查找成功！", ReturnResults.ACCESS_SUCCESS,employeeList);
        }
        return new Result("查找失败！", ReturnResults.ACCESS_FAILED);
    }

    @GetMapping("/userName")
    public Object findUserName(HttpServletRequest request){
        String token = request.getHeader("token");
        long employeeId = Long.parseLong(JWTUtil.parseToken(token).getPayload("employeeId").toString());
        String userName = employeeService.findUserName(employeeId);
        if (userName != null){
            return new Result("查找成功！", ReturnResults.ACCESS_SUCCESS,userName);
        }
        return new Result("查找失败！", ReturnResults.ACCESS_FAILED);

    }


    /**
     * 更新密码
     * @param oldLoginPassword
     * @param newLoginPassword
     * @param request
     * @return
     */
    @RequestMapping("/resetPwd")
    public Object updatePassword(@RequestBody PasswordUpdateRequest passwordUpdateRequest, HttpServletRequest request){
        String newLoginPassword =passwordUpdateRequest.getNewLoginPassword();
        String oldLoginPassword = passwordUpdateRequest.getOldLoginPassword();
        String token = request.getHeader("token");
        long employeeId = Long.parseLong(JWTUtil.parseToken(token).getPayload("employeeId").toString());
        int updated = employeeService.updatePassword(oldLoginPassword,newLoginPassword,employeeId);
        if (updated > 0 ){
            return new Result("修改成功！", ReturnResults.ACCESS_SUCCESS);
        }
        return new Result("修改失败！", ReturnResults.ACCESS_FAILED);
    }
}
